package net.oschina.app.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import net.oschina.app.R;
import net.oschina.app.bean.Constants;
import net.oschina.app.bean.News;
import net.oschina.app.bean.NewsDetail;
import net.oschina.app.util.MApp;
import net.oschina.app.util.StringUtils;
import net.oschina.app.util.URLGet;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by wuer on 2017/4/6/006.
 * 资讯详情
 */

public class NewsDetailActiviy extends AppCompatActivity {
    private NewsDetail newsDetail;//资讯详情
    private News news;//news
    private List<News.Relative> relatives = new ArrayList<News.Relative>();
    private Toolbar mNewsDetailToolbar;//toolbar
    private WebView mWebView;//webview
    private int detailId;//标题id
    private String detailTitle;//标题详情
    private TextView mTvTitle;//文本的标题
    private TextView mTvTime;//时间
    private TextView mTvAuthor;//作者
    private LinearLayout detailtoolbar;//底部6张图片
    private TextView mNum;//数量
    private LinearLayout detailtoolbarmore;//底部图片的处理


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newsdetail_activity);
        initView();
        initData();
    }

    private void initView() {
        mNewsDetailToolbar = (Toolbar) findViewById(R.id.news_detail_toolbar);//toolbar
        setSupportActionBar(mNewsDetailToolbar);
        /*mTvTitle = (TextView) findViewById(R.id.tv_title);//中间的标题
        mTvTime = (TextView) findViewById(R.id.tv_time); //时间
        mTvAuthor = (TextView) findViewById(R.id.tv_author);//作者*/
        mWebView = (WebView) findViewById(R.id.newsdetail_webView);//webView
        detailtoolbar = (LinearLayout) findViewById(R.id.ic_detail_toolbar);//底部
        detailtoolbarmore = (LinearLayout) findViewById(R.id.ic_detail_toolbar_more);//底部更多
    }

    private void initData() {
        //设置回退
        mNewsDetailToolbar.setNavigationIcon(R.drawable.actionbar_back_icon_normal);
        //设置title
        getSupportActionBar().setTitle("资讯详情");
        mNewsDetailToolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(mNewsDetailToolbar);
        mNewsDetailToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //获取id
        Intent intent = getIntent();
        detailId = intent.getIntExtra("id", 0);

        //获取网络数据
        URLGet urlGet = new URLGet();
        urlGet.getData(Constants.News_detail_Path + detailId + ".xml", NewsDetail.class, new URLGet.OnURLGetLitener<NewsDetail>() {
            public void showSuccess(final NewsDetail bean) {
                news = bean.getNews();
                relatives = news.getRelatives();
                MApp.mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                       // mTvTitle.setText(news.getTitle());
                        String str = news.getBody();
                        String url = news.getUrl();
                        //str.replace("http://10.0.2.2:8080", "http://10.0.3.2:8080:8080");//替换
                        WebSettings webSetting = mWebView.getSettings();
                        webSetting.setJavaScriptEnabled(true);
                        int num = news.getCommentCount();
                        if (num > 0) {
                            // mNum.setText(num + "");
                        }
                        mWebView.setWebViewClient(new MyWebViewClient());
                        //String webViewBody = getWebViewBody(news);
                        mWebView.loadUrl(url);
                        //mWebView.loadDataWithBaseURL(null,str, "text/html", "utf-8", null);
                        /*mNum.setText(news.getCommentCount() + "");
                        mTvTime.setText(news.getPubDate());
                        mTvAuthor.setText(news.getAuthor());*/
                    }
                });
            }

            @Override
            public void showError(Exception e) {
                System.out.println("出错啦");
            }
        });
    }

    //监听所有点击的链接，如果拦截到我们需要的，就跳转到相对应的页面。
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //这里进行url拦截
            if (url != null) {
                Intent intent = new Intent(NewsDetailActiviy.this, NewsDetailActiviy_web.class);
                intent.putExtra("detailTitle", detailTitle);
                intent.putExtra("url", url);
                NewsDetailActiviy.this.startActivity(intent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
        }
    }

    //动态添加,替换内容
    protected String getWebViewBody(News mDetail) {
        StringBuffer body = new StringBuffer();
        // 添加title
        body.append(String.format("<div class='title'>%s</div>", mDetail.getTitle()));
        // 添加作者和时间
        String time = StringUtils.friendly_time(mDetail.getPubDate());
        String author = String.format("<a class='author' href='http://my.oschina.net/u/%s'>%s</a>", mDetail.getAuthorId(), mDetail.getAuthor());
        body.append(String.format("<div class='authortime'>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</div>", author, time));
        //添加其他信息
        String softwareName = mDetail.getSoftwareName();
        String softwareLink = mDetail.getSoftwareLink();
        if (!StringUtils.isEmpty(softwareName)
                && !StringUtils.isEmpty(softwareLink))
            body.append(String
                    .format("<div class='oschina_software' style='margin-top:8px;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
                            softwareLink, softwareName));

        // 相关新闻
        if (mDetail != null && mDetail.getRelatives() != null
                && mDetail.getRelatives().size() > 0) {
            String strRelative = "";
            for (News.Relative relative : mDetail.getRelatives()) {
                strRelative += String.format(
                        "<li><a href='%s' style='text-decoration:none'>%s</a></li>",
                        relative.url, relative.title);
            }
            body.append("<p/><div style=\"height:1px;width:100%;background:#DADADA;margin-bottom:10px;\"/>"
                    + String.format("<br/> <b>相关资讯</b><ul class='about'>%s</ul>",
                    strRelative));
        }
        body.append("<br/>");
        // 追加
        body.append("</div></body>");
        return body.toString();
    }

    //底部点击事件
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_text:  //底部文字
                detailtoolbar.setVisibility(View.GONE);
                detailtoolbarmore.setVisibility(View.VISIBLE);
                break;
            case R.id.view_comment_layout://底部信息
                break;
            case R.id.iv_write://底部编辑
                detailtoolbar.setVisibility(View.GONE);
                detailtoolbarmore.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_favor://底部收藏
                finish();
                break;
            case R.id.iv_report1://底部返回
                finish();
                break;
            case R.id.iv_report2://底部警告
                finish();
                break;
        }
    }

    //设置刷新
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.refresh_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refresh_content:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

